<template>
  <div class="page">
    <h2>AI 对话</h2>
    <div class="chat-box">
      <div
        v-for="message in messages"
        :key="message.id"
        :class="['message', message.isUser ? 'user' : 'ai']"
      >
        <p>{{ message.text }}</p>
      </div>
    </div>
    <el-input
      v-model="userInput"
      placeholder="输入你的问题"
      @keyup.enter="sendMessage"
      clearable
      class="input-field"
    />
    <el-button type="primary" @click="sendMessage" class="send-button">
      发送
    </el-button>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, onMounted } from 'vue';
import { useChatStore } from '@/stores/chatStore';

export default defineComponent({
  setup() {
    const userInput = ref('');
    const chatStore = useChatStore();
    const messages = chatStore.messages;

    const sendMessage = () => {
      if (userInput.value.trim()) {
        chatStore.addUserMessage(userInput.value);
        chatStore.fetchAiResponse(userInput.value);
        userInput.value = '';
      } else {
        alert('请输入信息');
      }
    };

    onMounted(() => {
      chatStore.addAiMessage('我是您的AI助手，有什么不懂的问题尽管问我吧！');
    });

    return {
      userInput,
      messages,
      sendMessage,
    };
  },
});
</script>

<style scoped>
.page {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  padding: 20px;
  background-color: #f5f5f5;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

h2 {
  margin-bottom: 20px;
  font-size: 1.8rem;
  color: #333;
}

.chat-box {
  width: 100%;
  max-width: 500px;
  height: 400px;
  margin-bottom: 20px;
  padding: 10px;
  border: 1px solid #34495e;
  border-radius: 8px;
  background-color: #2c3e50;
  overflow-y: auto;
}

.message {
  margin: 10px 0;
  padding: 10px;
  border-radius: 8px;
  background-color: #34495e;
  color: #ecf0f1;
  word-wrap: break-word;
}

.message.user {
  background-color: #1abc9c;
  align-self: flex-end;
}

.message.ai {
  background-color: #3b3f4a;
  align-self: flex-start;
}

.input-field {
  width: 100%;
  max-width: 500px;
  margin-bottom: 10px;
}

.send-button {
  width: 100%;
  max-width: 150px;
}
</style>